package com.compty.paint.freemarker.support;

import java.util.Comparator;

import com.compty.paint.domain.Painter;

public class PainterComparator implements Comparator<Painter> {
	
	public int compare(Painter o1, Painter o2) {
		
		if(o1 == null ){
			return -1;
		}
		
		if(o2 == null){
			return 1;
		}
		
		if(o1.getNewestIndex() == null){
			return -1;
		}
		
		if(o2.getNewestIndex() == null){
			return 1;
		}
		
		String price1 = o1.getNewestIndex().getPrice().trim();
		String price2 = o2.getNewestIndex().getPrice().trim();
		
		int price1_int = parsePriceToInt(price1);
		int price2_int = parsePriceToInt(price2);
		if ( price1_int > price2_int) {
			return 1;
		} else if (price1_int == price2_int) {
				return 0;
		} else if (price1_int < price2_int) {
			return -1;
		}else{
			return -1;
		}
	}
	
	int parsePriceToInt(String price){
		if(price == null || "".equals(price)){
			return 0;
		}else{
			char[] charArray = price.toCharArray();
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < charArray.length; i++) {
				if(Character.isDigit(charArray[i])){
					sb.append(charArray[i]);
				}
			}
			
			String result = sb.toString();
			if(!"".equals(result)){
				return Integer.parseInt(result);
			}else{
				return 0;
			}
		}
	}
}